package com.example.dynamicschedule.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.dynamicschedule.base.CreditResultDTO;
import com.example.dynamicschedule.bean.*;
import com.example.dynamicschedule.dao.*;
import com.example.dynamicschedule.dao.CkFeedbackConfigTableMapper;
import com.example.dynamicschedule.dao.CkOrderLoanPeopleDivisionMapper;
import com.example.dynamicschedule.dao.CkOrderOutboundRecoveryLogMapper;
import com.example.dynamicschedule.dao.CkStopNoticePersonTimesMapper;
import com.example.dynamicschedule.utils.FileDownloadUtil;
import com.example.dynamicschedule.utils.NoAnswerAndMissPeopleUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class IntelligenceCallService {

    @Autowired
    private CkOrderRecoveryDataService ckOrderRecoveryDataService;
    @Autowired
    private CkOrderNotDialedService ckOrderNotDialedService;
    @Autowired
    private CkOrderOutboundRecoveryLogMapper ckOrderOutboundRecoveryLogMapper;
    @Autowired
    private FileDownloadUtil fileDownloadUtil;
    @Autowired
    private CkOrderLoanPeopleDivisionMapper ckOrderLoanPeopleDivisionMapper;
    @Autowired
    private NoAnswerAndMissPeopleUtils noAnswerAndMissPeopleUtils;
    @Autowired
    private CkFeedBackService ckFeedBackService;
    @Autowired
    private CkStopNoticePersonService ckStopNoticePersonService;
    @Autowired
    private CkOrderLoanIntelligenceDivisionService ckOrderLoanIntelligenceDivisionService;
    @Autowired
    private CkCreditLogMapper ckCreditLogMapper;
    @Autowired
    private CkFeedBackService feedBackService;
    @Autowired
    private CkCreditStopNoticePersonMapper ckCreditStopNoticePersonMapper;
    @Autowired
    private CkCreditAccountInfoMapper ckCreditAccountInfoMapper;
    @Autowired
    private CkStopNoticePersonTimesMapper ckStopNoticePersonTimesMapper;
    @Autowired
    private CkFeedbackConfigTableMapper ckFeedbackConfigTableMapper;
    static org.apache.log4j.Logger logger = Logger.getLogger(IntelligenceCallService.class);
    /**
     * 智能外呼反馈数据处理
     * @param filePath
     * @param feedBackConfigMap
     * @throws Exception
     */
    public void intelligenceCallService(String filePath, Map<String, CkFeedbackConfigTable> feedBackConfigMap) throws Exception {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat1.format(date);
        logger.info("智能外呼处理开始,参数为:"+filePath);
        logger.info("读取json文件开始");
        String intelligenceJsonStr =fileDownloadUtil.readJSONFile(filePath);
        logger.info("读取json文件结束,json文件为:"+intelligenceJsonStr);
        logger.info("处理未接及已接数据开始");
        JSONObject jsonObject = JSONObject.parseObject(intelligenceJsonStr);
        Object intelligenceObject = jsonObject.get("智能外呼");
        List<CkOrderRecoveryData> ckOrderRecoveryDataList = JSON.parseArray(JSON.toJSONString(intelligenceObject), CkOrderRecoveryData.class);
        logger.info("筛选人工分案开始");
        List<String> serialNumbers = ckOrderLoanPeopleDivisionMapper.findSerialNumberByDataTime(format);
        if (CollectionUtils.isNotEmpty(serialNumbers)) {
            Iterator<CkOrderRecoveryData> iterator = ckOrderRecoveryDataList.iterator();
            while (iterator.hasNext()) {
                CkOrderRecoveryData next = iterator.next();
                String serialNumber = next.getSerialNumber();
                if (serialNumbers.contains(serialNumber)) {
                    iterator.remove();
                }
            }
        }
        logger.info("筛选人工分案结束");
        CkStopNoticePersonTimes ckStopNoticePersonTimes= ckStopNoticePersonTimesMapper.selectByKey("noAnswerPeople");
        Map<String, Integer> noAnswerPeopleMap = null;
        if (ckStopNoticePersonTimes!=null) {
            String value = ckStopNoticePersonTimes.getMapValue();
            // Map<Object, Object> noAnswerPeople = redisService.hmget("noAnswerPeople");
            noAnswerPeopleMap = JSON.parseObject(value, Map.class);
        } else {
            noAnswerPeopleMap = new HashMap<>();
            ckStopNoticePersonTimes=new CkStopNoticePersonTimes();
        }
        CkFeedbackConfigTable ckFeedbackConfigTable = ckFeedbackConfigTableMapper.selectByType((byte) 3);
        String noAnswer = ckFeedbackConfigTable.getNumbers();
        //已接电话
        List<CkOrderRecoveryData> ckOrderRecoveryDatas = new ArrayList<>();
        //未接电话
        List<CkOrderNotDialed> ckOrderNotDialedList = new ArrayList<>();
        for (CkOrderRecoveryData ckOrderRecoveryData : ckOrderRecoveryDataList) {
            String feedbackCode = ckOrderRecoveryData.getFeedbackCode();
            if (StringUtils.isNotEmpty(feedbackCode)) {
                ckOrderRecoveryData.setNotificationMethod((byte) 2);
                ckOrderRecoveryData.setSendTime(format);
                ckOrderRecoveryDatas.add(ckOrderRecoveryData);
                //连续三次问题
                if (noAnswerPeopleMap != null&&noAnswerPeopleMap.size()>0) {
                    String serialNumber = ckOrderRecoveryData.getSerialNumber();
                    if (noAnswerPeopleMap.get(serialNumber) != null) {
                        if (!noAnswer.contains(feedbackCode)) {
                            noAnswerPeopleMap.remove(serialNumber);
                        }
                    }
                }
            } else {
                CkOrderNotDialed ckOrderNotDialed = new CkOrderNotDialed();
                BeanUtils.copyProperties(ckOrderRecoveryData,ckOrderNotDialed);
                ckOrderNotDialed.setNotificationMethod((byte)2);
                ckOrderNotDialedList.add(ckOrderNotDialed);
            }
        }
        ckStopNoticePersonTimes.setMapValue(JSON.toJSONString(noAnswerPeopleMap));
        logger.info("处理未接及已接数据结束");
        logger.info("获取反馈码分类开始");

      /*  Map feedBackConfigMap=null;
        if (redisService.hasKey("feedBackConfig")) {
            Object feedBackConfig = redisService.get("feedBackConfig");
            feedBackConfigMap =  JSONObject.parseObject(feedBackConfig.toString(), Map.class);
            //feedBackConfigMap = JSON.parseObject(JSON.toJSONString(feedBackConfig), Map.class);
        } else {
            feedBackConfigMap = ckFeedBackConfigService.selectList();
        }*/
        logger.info("获取反馈码分类结束");
        //停催反馈码
        CkFeedbackConfigTable stopCkFeedbackConfigTable = feedBackConfigMap.get("停催");
        //CkFeedbackConfigTable stopCkFeedbackConfigTable = JSON.parseObject(JSON.toJSONString(stopCkFeedbackConfigTableObject), CkFeedbackConfigTable.class);
        String stopNumbers = stopCkFeedbackConfigTable.getNumbers();
        //失联反馈码
        CkFeedbackConfigTable missCkFeedbackConfigTable = feedBackConfigMap.get("失联");
       // CkFeedbackConfigTable missCkFeedbackConfigTable = JSONObject.parseObject(JSON.toJSONString(missCkFeedbackConfigTableObject),CkFeedbackConfigTable.class);
        String missNumbers = missCkFeedbackConfigTable.getNumbers();
        logger.info("判断失联表中是否出现成功联系开始");
        List<CkStopNoticePerson> contactCkStopNoticePeople = noAnswerAndMissPeopleUtils.answerPeople(ckOrderRecoveryDataList,stopNumbers,missNumbers);
        logger.info("在失联表中物理删除开始");
        if (!org.springframework.util.CollectionUtils.isEmpty(contactCkStopNoticePeople)) {
            ckStopNoticePersonService.updateForeach(contactCkStopNoticePeople);
        }
        logger.info("在失联表中物理删除结束");
        logger.info("判断失联表中是否出现成功联系结束");
        logger.info("处理未接电话三次变为失联开始");
       // String noAnswer = ckFeedBackService.selectByChinese("未接听");
        List<CkStopNoticePerson> ckStopNoticePeopleList = new ArrayList<>();
        ckStopNoticePeopleList=noAnswerAndMissPeopleUtils.noAnswerThree(ckOrderRecoveryDatas,noAnswer,
                ckStopNoticePeopleList,ckStopNoticePersonTimes);
        logger.info("处理未接电话三次变为失联结束");
      /*  logger.info("判断失联连续三次为停催开始");
        List<CkStopNoticePerson> threes = noAnswerAndMissPeopleUtils.missPeopleThree(ckStopNoticePeopleList);
        logger.info("判断失联连续三次为停催结束");
        logger.info("存储失联变为停催数据开始");
        if (!org.springframework.util.CollectionUtils.isEmpty(threes)) {
            ckStopNoticePersonService.updateForeachBySeriaNumber(threes);
        }
        logger.info("存储失联变为停催数据结束");*/
        logger.info("失联表存储开始");
        if (!org.springframework.util.CollectionUtils.isEmpty(ckStopNoticePeopleList)) {
            ckStopNoticePersonService.insertForeach(ckStopNoticePeopleList);
        }
        logger.info("失联表存储结束");
        logger.info("更新已接电话开始");
        if (CollectionUtils.isNotEmpty(ckOrderRecoveryDatas)) {
            List<String> serialNumberList = new ArrayList<>();
            List<String> serialNumberList1 = new ArrayList<>();
            for (CkOrderRecoveryData ckOrderRecoveryData : ckOrderRecoveryDatas) {
                String feedbackCode = ckOrderRecoveryData.getFeedbackCode();
                String serialNumber = ckOrderRecoveryData.getSerialNumber();
                if (!noAnswer.contains(feedbackCode)) {
                    serialNumberList.add(serialNumber);
                }
                serialNumberList1.add(serialNumber);
            }
            List<CkOrderLoanIntelligenceDivision> ckOrderLoanIntelligenceDivisions = ckOrderLoanIntelligenceDivisionService.selectBySerialNumbers(serialNumberList);
            if (CollectionUtils.isNotEmpty(ckOrderLoanIntelligenceDivisions)) {
                ckOrderLoanIntelligenceDivisions.stream().forEach(ckOrderLoanIntelligenceDivision -> ckOrderLoanIntelligenceDivision.setIsDialed(1));
                ckOrderLoanIntelligenceDivisionService.updateForEach(ckOrderLoanIntelligenceDivisions);
            }
            //2021-02-01
            logger.info("因多次操作会出现多条记录故若有记录删除");
            List<CkOrderRecoveryData> intelligenceDivisionCkOrderRecoveryData=ckOrderRecoveryDataService.selectBySerialNumbers(serialNumberList1,"%"+format+"%");
            if (!org.springframework.util.CollectionUtils.isEmpty(intelligenceDivisionCkOrderRecoveryData)) {
                ckOrderRecoveryDataService.deleteForEach(intelligenceDivisionCkOrderRecoveryData);
            }
        }
        logger.info("更新已接电话结束");
        logger.info("存储已接电话开始");
        if (CollectionUtils.isNotEmpty(ckOrderRecoveryDatas)) {
            ckOrderRecoveryDataService.insertForeach(ckOrderRecoveryDatas);
        }
        logger.info("存储已接电话结束");

        logger.info("存储未接电话开始");
        if (CollectionUtils.isNotEmpty(ckOrderNotDialedList)) {
            ckOrderNotDialedService.insertForeach(ckOrderNotDialedList);
        }
        logger.info("存储未接电话结束");
        logger.info("存储智能外呼到log表开始");
        CkOrderOutboundRecoveryLog ckOrderOutboundRecoveryLog = new CkOrderOutboundRecoveryLog();
        ckOrderOutboundRecoveryLog.setDataTime(format);
        ckOrderOutboundRecoveryLog.setOutboundType("智能外呼");
        ckOrderOutboundRecoveryLog.setStatus((byte) 1);
        ckOrderOutboundRecoveryLogMapper.insert(ckOrderOutboundRecoveryLog);
        logger.info("存储智能外呼到log表结束");
    }

    /**
     * 信贷拉去三方处理
     * @param localPath 三方下载文件地址(服务器)
     * @param feedBackConfigMap 失联和停催反馈码
     * @param ckCreditLogs 今天下发的所有除委外以外的log表
     * @param noDia 未接听反馈码
     * @param stopCkCreditStopNoticePeoples 失联名单信息(成功联系出催)
     */
    public void creditIntelligenceCall(String localPath, Map<String,
            CkFeedbackConfigTable> feedBackConfigMap,
                                       List<CkCreditLog> ckCreditLogs,
                                       String noDia,
                                       List<CkCreditStopNoticePerson> stopCkCreditStopNoticePeoples,
                                       String outCallMethod,
                                       String noCall) throws Exception {

        logger.info("信贷下载任务---------外呼处理----------------开始,本地数据地址为"+localPath);
        logger.info("信贷下载任务---------读取json文件----------------开始");
        String intelligenceJsonStr=null;
        if ("智能外呼".equalsIgnoreCase(outCallMethod)) {
            intelligenceJsonStr = fileDownloadUtil.readJSONFile(localPath);
        } else {
            intelligenceJsonStr=fileDownloadUtil.readESBJsonFile(localPath);
        }

        logger.info("信贷下载任务---------读取json文件----------------结束,json文件为:"+intelligenceJsonStr);
        if (StringUtils.isNotEmpty(intelligenceJsonStr)) {
            logger.info("信贷下载任务---------处理未接及已接数据----------------开始");
            JSONObject jsonObject = JSONObject.parseObject(intelligenceJsonStr);
            Object intelligenceObject = jsonObject.get(outCallMethod);
            List<CreditResultDTO> creditResultDTOList = JSON.parseArray(JSON.toJSONString(intelligenceObject), CreditResultDTO.class);
            //当天全部的log表
            Map<String, CkCreditLog> ckCreditLogHashMap = new HashMap<>();
            for (CkCreditLog ckCreditLog : ckCreditLogs) {
                String serialNumber = ckCreditLog.getSerialNumber();
                ckCreditLogHashMap.put(serialNumber, ckCreditLog);
            }
            //停催所对应的map
            Map<String, CkCreditStopNoticePerson> ckCreditStopNoticePersonMap = new HashMap<>();
            for (CkCreditStopNoticePerson stopCkCreditStopNoticePeople : stopCkCreditStopNoticePeoples) {
                String identificationNumber = stopCkCreditStopNoticePeople.getIdentificationNumber();
                ckCreditStopNoticePersonMap.put(identificationNumber, stopCkCreditStopNoticePeople);
            }
            //停催失联的反馈码
            CkFeedbackConfigTable stop = feedBackConfigMap.get("停催");
            String stopNumbers = stop.getNumbers();
            CkFeedbackConfigTable notice = feedBackConfigMap.get("失联");
            String noticeNumbers = notice.getNumbers();
            //存储停催或者失联数据
            List<CkCreditStopNoticePerson> ckCreditStopNoticePeoples = new ArrayList<>();
            //存储未接听数据
            List<CreditResultDTO> noCallCkCreditResultDTOs = new ArrayList<>();
            //存储未拨打数据
            List<CreditResultDTO> noDiaCreditResultDTOs = new ArrayList<>();
            //存储全部数据
            List<CkCreditLog> allCkCreditLogs = new ArrayList<>();
            //存储失联成功联系list
            List<CkCreditStopNoticePerson> sussessCkCreditStopNoticePersons = new ArrayList<>();
            for (CreditResultDTO creditResultDTO : creditResultDTOList) {
                String feedbackCode = creditResultDTO.getFeedbackCode();
                String serialNumber = creditResultDTO.getSerialNumber();
                CkCreditLog ckCreditLog = ckCreditLogHashMap.get(serialNumber);

                if (ckCreditLog == null) {
                    logger.info("信贷下载任务---------获取log表数据----------------数据为空,案件号为:"+serialNumber);
                    continue;
                }
               /* if (creditResultDTO.getCollectionTime() == null) {
                    ckCreditLog.setCollectionTime(new Date());
                } else {
                    ckCreditLog.setCollectionTime(creditResultDTO.getCollectionTime());
                }*/
                ckCreditLog.setCurrentDate(new Date());
                ckCreditLog.setContactObject(creditResultDTO.getContactObject());
                ckCreditLog.setTalkBegin(creditResultDTO.getTalkBegin());
                ckCreditLog.setTalkEnd(creditResultDTO.getTalkEnd());
                ckCreditLog.setTalkTime(creditResultDTO.getTalkTime());
                ckCreditLog.setCustomerServiceId(creditResultDTO.getCustomerServiceId());
                ckCreditLog.setCustomerServiceName(creditResultDTO.getCustomerServiceName());
                ckCreditLog.setFeedbackCode(feedbackCode);
                ckCreditLog.setTimeStamp(creditResultDTO.getTimeStamp());
                ckCreditLog.setExternalCallSign(creditResultDTO.getExternalCallSign());
                ckCreditLog.setContactObject(creditResultDTO.getContactObject());
                ckCreditLog.setCollectionRecord(creditResultDTO.getCollectionRecord());
                ckCreditLog.setRemarks(creditResultDTO.getRemarks());
                ckCreditLog.setTimeStamp(creditResultDTO.getTimeStamp());
                ckCreditLog.setMinimumOutstandingAmount(creditResultDTO.getMinimumOutstandingAmount());
                ckCreditLog.setOldCardNumber(creditResultDTO.getOldCardNumber());
                ckCreditLog.setHomeNumberStatus(creditResultDTO.getHomeNumberStatus());
                ckCreditLog.setPhoneNumberStatus(creditResultDTO.getPhoneNumberStatus());
                ckCreditLog.setPhoneNumberOfContactOneStatus(creditResultDTO.getPhoneNumberOfContactOneStatus());
                ckCreditLog.setPhoneNumberOfContactTwoStatus(creditResultDTO.getPhoneNumberOfContactTwoStatus());
                ckCreditLog.setOtherContactPhoneNumberStatus(creditResultDTO.getOtherContactPhoneNumberStatus());
                ckCreditLog.setWorkNumberStatus(creditResultDTO.getWorkNumberStatus());
                if (StringUtils.isEmpty(feedbackCode)) {
                    //记录未拨打记录
                    ckCreditLog.setFeedbackCode(noDia);
                    allCkCreditLogs.add(ckCreditLog);
                    noDiaCreditResultDTOs.add(creditResultDTO);
                } else {
                    //停催
                    if (stopNumbers.contains(feedbackCode)) {
                        CkCreditStopNoticePerson ckCreditStopNoticePerson = new CkCreditStopNoticePerson();
                        BeanUtils.copyProperties(creditResultDTO, ckCreditStopNoticePerson);
                        ckCreditStopNoticePerson.setStatus(2);
                        ckCreditStopNoticePerson.setDele(feedbackCode);
                        ckCreditStopNoticePerson.setDataTime(new Date());
                        ckCreditStopNoticePeoples.add(ckCreditStopNoticePerson);
                        ckCreditStopNoticePerson = null;
                        //失联
                    } else if (noticeNumbers.contains(feedbackCode)) {
                        CkCreditStopNoticePerson ckCreditStopNoticePerson = new CkCreditStopNoticePerson();
                        BeanUtils.copyProperties(creditResultDTO, ckCreditStopNoticePerson);
                        ckCreditStopNoticePerson.setStatus(1);
                        ckCreditStopNoticePerson.setDele(feedbackCode);
                        ckCreditStopNoticePerson.setDataTime(new Date());
                        ckCreditStopNoticePeoples.add(ckCreditStopNoticePerson);
                        ckCreditStopNoticePerson = null;
                    } else if (feedbackCode.equalsIgnoreCase(noCall)) {
                        noCallCkCreditResultDTOs.add(creditResultDTO);
                    }
                    CkCreditStopNoticePerson ckCreditStopNoticePerson = ckCreditStopNoticePersonMap.get(creditResultDTO.getIdentificationNumber());
                    if (ckCreditStopNoticePerson != null) {
                        ckCreditStopNoticePerson.setStatus(3);
                        sussessCkCreditStopNoticePersons.add(ckCreditStopNoticePerson);
                    }
                    allCkCreditLogs.add(ckCreditLog);
                }
            }
            creditResultDTOList.clear();
            logger.info("信贷下载任务---------处理未接及已接数据----------------结束");
            logger.info("信贷下载任务---------未接三次变为失联----------------开始");
            List<CkCreditAccountInfo> ckCreditAccountInfos = new ArrayList<>();
            for (CreditResultDTO creditResultDTO : noCallCkCreditResultDTOs) {
                String serialNumber = creditResultDTO.getSerialNumber();
                int count = ckCreditLogMapper.selectByThreeDaysStopPerson(serialNumber);
                if (count < 3) {
                    String cardNumber = creditResultDTO.getCardNumber();
                    CkCreditAccountInfo ckCreditAccountInfo = new CkCreditAccountInfo();
                    ckCreditAccountInfo.setCardNumber(cardNumber);
                    ckCreditAccountInfo.setNorm(null);
                    ckCreditAccountInfos.add(ckCreditAccountInfo);
                }
            }
            noCallCkCreditResultDTOs.clear();
            ckCreditStopNoticePersonMap.clear();
            logger.info("信贷下载任务---------未接三次变为失联----------------结束");
            logger.info("信贷下载任务---------未拨打及未接听更新卡信息表----------------开始");
            if (CollectionUtils.isNotEmpty(noDiaCreditResultDTOs)) {
                for (CreditResultDTO noDiaCreditResultDTO : noDiaCreditResultDTOs) {
                    String cardNumber = noDiaCreditResultDTO.getCardNumber();
                    CkCreditAccountInfo ckCreditAccountInfo = new CkCreditAccountInfo();
                    ckCreditAccountInfo.setCardNumber(cardNumber);
                    ckCreditAccountInfo.setNorm(null);
                    ckCreditAccountInfos.add(ckCreditAccountInfo);
                }
                ckCreditAccountInfoMapper.updateByCardNumberForEach(ckCreditAccountInfos);
            }
            logger.info("信贷下载任务---------未拨打及未接听更新卡信息表----------------结束");
            if (CollectionUtils.isNotEmpty(ckCreditStopNoticePeoples)) {
                logger.info("信贷下载任务---------存储失联和停催名单----------------开始");
                ckCreditStopNoticePersonMapper.insertForEach(ckCreditStopNoticePeoples);
                ckCreditStopNoticePeoples.clear();
                logger.info("信贷下载任务---------存储失联和停催名单----------------结束");
            }
            if (CollectionUtils.isNotEmpty(allCkCreditLogs)) {
                logger.info("信贷下载任务---------更新log表反馈吗----------------开始");
                ckCreditLogMapper.updateForEach(allCkCreditLogs);
                allCkCreditLogs.clear();
                logger.info("信贷下载任务---------更新log表反馈吗----------------结束");
            }
            if (CollectionUtils.isNotEmpty(sussessCkCreditStopNoticePersons)) {
                logger.info("信贷下载任务---------成功联系出停催表----------------开始");
                ckCreditStopNoticePersonMapper.updateForEach(sussessCkCreditStopNoticePersons);
                logger.info("信贷下载任务---------成功联系出停催表----------------结束");
            }
            logger.info("信贷下载任务-------------------------结束");
        } else {
            logger.info("信贷下载任务-------------------------结束,json文件为空");
        }
    }

}
